package org.farm2.ai.test.funcall;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import com.fasterxml.jackson.databind.JsonNode;
import org.farm2.ai.call.tools.MockWeatherService;
import org.farm2.ai.test.config.ApiConfig;
import org.farm2.ai.utils.SimpleConsoleAdvisor;
import org.farm2.base.db.process.FarmProcessUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.model.function.FunctionCallback;
import reactor.core.publisher.Flux;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;


public class CallFunctionDemo {
    public static void main(String[] args) {
        ChatClient client = getClient();
        sendMsg(client, "你好，今天太原天气怎么样");
    }

    public static ChatClient getClient() {
        String apiKey = ApiConfig.apiKey;
        // 创建 DashScope API 客户端
        DashScopeApi dashScopeApi = new DashScopeApi(apiKey);
        // 构建 ChatOptions（可选参数）
        DashScopeChatOptions options = DashScopeChatOptions.builder().withModel("qwen-turbo")     // 使用的模型名称
                .withTopP(0.7).withTemperature(0.9).build();
        // 手动创建 ChatModel 实例
        ChatModel chatModel = new DashScopeChatModel(dashScopeApi, options);

        ChatClient chatClient = ChatClient.builder(chatModel).defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory())).defaultAdvisors(new SimpleConsoleAdvisor()).defaultFunctions(getFunctions().toArray(new FunctionCallback[0])).build();
        return chatClient;
    }


    public static void sendMsg(ChatClient chatClient, String msg) {
        Flux<String> output = chatClient.prompt().user(msg)//.system("你叫小明是个10岁小朋友！")
                .stream().content();


//        // ⬇️ 订阅流并打印结果
        output.subscribe(System.out::println, error -> System.out.println(error.getMessage()), () -> {
            System.out.println("over");
        });
        // 等待流完成
        output.blockLast();
        System.out.println("\n-");
        FarmProcessUtils.sleep(2000);
    }

    public static List<FunctionCallback> getFunctions() {
        return List.of(new FunctionCallback() {
            @Override
            public String getName() {
                return "getWeather";
            }

            @Override
            public String getDescription() {
                return "获得今天的天气";
            }

            @Override
            public String getInputTypeSchema() {
                return """
                            {
                              "type": "object",
                              "properties": {
                                "city": {
                                  "type": "string",
                                  "description": "要查询天气的城市名称"
                                }
                              },
                              "required": ["city"]
                            }
                        """;
            }

            @Override
            public String call(String functionInput) {
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode jsonNode = objectMapper.readTree(functionInput);
                    String city = jsonNode.has("city") ? jsonNode.get("city").asText() : "未知城市";
                    // 调用 Mock 天气服务
                    System.out.println("查询城市:" + city);
                    return "今天天气-" + city + ":气温20-25°C，大太阳，雨夹雪啊";
                } catch (Exception e) {
                    return "解析城市信息失败: " + e.getMessage();
                }
            }
        });
    }
}
